package com.mindbook.vip.gawxchatinfo.utils;

import com.mindbook.vip.gawxchatinfo.utils.properties.ApplicationContextUtil;

import javax.crypto.Cipher;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

/**
 * @NAME: wxb
 * @DATE: 2022/5/20
 * @DESCRIPTION: RSA工具类
 *  但是，只包含解密操作，不包括加密操作
 *
 **/
public class RsaUtils {

    /**
     * RSA 解密
     * @param data
     * @return
     * @throws GeneralSecurityException
     */
    public static String decrypt(String data ) throws GeneralSecurityException {
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(base64Decode(ApplicationContextUtil.getProperty("rsa.encrypt.privateKey")));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, keyFactory.generatePrivate(keySpec));
        return new String(cipher.doFinal(base64Decode(data.replace("\r\n",""))));
    }

    static byte[] base64Decode(String str) {
        return Base64.getMimeDecoder().decode(str);
    }

}
